<template>
  <view class="savepadding">
    <view class="step-bg">
      <text :style="{
          border: 0 == selType ? '#1573FF 1rpx solid' : '#a7a7a7 1rpx solid',
          color: 0 == selType ? '#1573FF' : '#333',
        }"
            @click="selType = 0">个人客户
      </text>
      <text :style="{
          border: 1 == selType ? '#1573FF 1rpx solid' : '#a7a7a7 1rpx solid',
          color: 1 == selType ? '#1573FF' : '#333',
        }"
            style="margin-left: 150rpx" @click="selType = 1">企业客户
      </text>
    </view>

    <view class="item" style="padding: 20rpx">
      <u-form :model="addbean" ref="uForm" label-width="auto" :rules="rules">
        <view class="">
          <u-icon name="order" color="#1573FF" label="基本信息" label-color="#333333"></u-icon>
        </view>
        <u-form-item>
          <view class="pic-content">
            <view class="pic-item">
              <lr-upload tag="1" width="280rpx" height="200rpx" uploadType="2"
                         addBtnImage="../../static/car/addCar_driverCard.png"
                         @on-change="uploadOnChange">
              </lr-upload>
              <text>身份证正面</text>
            </view>

            <view class="pic-item">
              <lr-upload tag="2" width="280rpx" height="200rpx" uploadType="2"
                         addBtnImage="../../static/car/addCar_driverCard.png"
                         @on-change="uploadOnChange">
              </lr-upload>
              <text>身份证背面</text>
            </view>

            <view class="pic-item">
              <lr-upload tag="3" width="280rpx" height="200rpx" uploadType="2"
                         addBtnImage="../../static/car/addCar_driverCard.png"
                         @on-change="uploadOnChange">
              </lr-upload>
              <text>驾驶证正页</text>
            </view>

            <view class="pic-item">
              <lr-upload tag="4" width="280rpx" height="200rpx" uploadType="2"
                         addBtnImage="../../static/car/addCar_driverCard.png"
                         @on-change="uploadOnChange">
              </lr-upload>
              <text>驾驶证副页</text>
            </view>

            <view class="pic-item" v-if="selType === 1">
              <lr-upload tag="5" width="280rpx" height="200rpx" uploadType="2"
                         addBtnImage="../../static/car/addCar_driverCard.png"
                         @on-change="uploadOnChange">
              </lr-upload>
              <text>营业执照</text>
            </view>
          </view>
        </u-form-item>

        <u-form-item label="客户名称" borderBottom prop="customerName" required>
          <u-input v-model="addbean.customerName" inputAlign="right" border="none" :placeholder="
              selType == 1 ? '请输入企业名称' : '上传身份证自动获取'
            ">
          </u-input>
        </u-form-item>

        <u-form-item label="客户编号" borderBottom>
          <u-input v-model="addbean.customerNo" inputAlign="right" border="none" :placeholder="
              selType == 1 ? '请输入客户编号' : '上传身份证自动获取'
            ">
          </u-input>
        </u-form-item>

        <u-form-item label="联系电话" required borderBottom prop="contactMobile">
          <u-input v-model="addbean.contactMobile" type="number" maxlength="11" inputAlign="right" border="none"
                   placeholder="请输入联系电话">
          </u-input>
        </u-form-item>


        <u-form-item label="身份证号" :required="isRequire(`idCardNo`)" borderBottom prop="idCardNo">
          <u-input v-model="addbean.idCardNo" type="idcard" inputAlign="right" border="none"
                   placeholder="上传身份证自动获取">
          </u-input>
        </u-form-item>

        <u-form-item label="联系人" borderBottom required prop="contactPerson">
          <u-input v-model="addbean.contactPerson" inputAlign="right" border="none" placeholder="请输入联系人">
          </u-input>
        </u-form-item>

        <u-form-item label="身份证失效日期" borderBottom>
          <u-input v-model="addbean.idCardExpirydate" inputAlign="right" border="none" placeholder="上传身份证自动获取">
          </u-input>
        </u-form-item>

        <u-form-item label="驾驶证号" borderBottom>
          <u-input v-model="addbean.driverNo" inputAlign="right" border="none" placeholder="上传驾驶证自动获取">
          </u-input>
        </u-form-item>

        <u-form-item label="驾驶证有效期" borderBottom>
          <u-input v-model="addbean.driverValidity" inputAlign="right" border="none" placeholder="上传驾驶证自动获取">
          </u-input>
        </u-form-item>

        <u-form-item label="准驾车型" borderBottom>
          <u-input v-model="addbean.quasiDrivingType" inputAlign="right" border="none" placeholder="请输入准驾车型">
          </u-input>
        </u-form-item>

        <u-form-item label="紧急联系人" prop="emergencyPerson" :required="isRequire(`emergencyPerson`)" borderBottom>
          <u-input v-model="addbean.emergencyPerson" inputAlign="right" border="none" placeholder="请输入紧急联系人">
          </u-input>
        </u-form-item>

        <u-form-item label="紧急联系电话" prop="emergencyMobile" :required="isRequire(`emergencyMobile`)">
          <u-input v-model="addbean.emergencyMobile" inputAlign="right" type="number" maxlength="11" border="none"
                   placeholder="请输入紧急联系电话">
          </u-input>
        </u-form-item>

        <view v-if="selType === 1">
          <u-form-item label="营业执照" borderBottom>
            <u-input v-model="addbean.license" inputAlign="right" border="none" placeholder="请输入营业执照">
            </u-input>
          </u-form-item>

          <u-form-item label="公司地址" borderBottom>
            <u-input v-model="addbean.address" inputAlign="right" border="none" placeholder="请输入公司地址">
            </u-input>
          </u-form-item>
        </view>

        <view v-if="selType === 0">
          <u-form-item label="性别" borderBottom @click="openShow('show')">
            <u-input :value="handleLabel(addbean.sex,columnsSexList)" disabled
                     disabledColor="#ffffff"
                     placeholder="请选择性别"
                     border="none"
                     inputAlign="right"
            ></u-input>
            <u-icon slot="right" name="arrow-right"></u-icon>
            <u-picker :show="show" :columns="columnsSexList" @confirm="confirmSex" @cancel="show = false"/>
          </u-form-item>

          <u-form-item label="生日" borderBottom @click="handeClick('1')">
            <u-input v-model="addbean.birthday" inputAlign="right" disabled disabledColor="#ffffff"
                     border="none"
                     placeholder="请选择" type="select"></u-input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>

          <u-form-item label="联系地址" borderBottom>
            <u-input v-model="addbean.address" inputAlign="right" border="none" placeholder="上传身份证自动获取">
            </u-input>
          </u-form-item>

          <u-form-item label="现在住址" borderBottom>
            <u-input v-model="addbean.nowAddress" inputAlign="right" border="none" placeholder="请输入详细地址">
            </u-input>
          </u-form-item>
        </view>

        <u-form-item label="邮箱" borderBottom>
          <u-input v-model="addbean.email" inputAlign="right" border="none" placeholder="请输入邮箱">
          </u-input>
        </u-form-item>

        <u-form-item label="所属业务负责人" borderBottom @click="selRes">
          <u-input v-model="addbean.username" inputAlign="right" disabled disabledColor="#ffffff" border="none"
                   placeholder="请选择所属业务负责人">
          </u-input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>

        <u-form-item label="所属渠道商" borderBottom @click="selchannel">
          <u-input v-model="addbean.channelName" inputAlign="right" disabled disabledColor="#ffffff" border="none"
                   placeholder="请选择所属渠道商">
          </u-input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>

        <u-form-item label="客户来源" borderBottom @click="openShow('showC')">
          <u-input :value="handleLabel(addbean.customerSource,customerSource)" inputAlign="right" border="none"
                   disabledColor="#ffffff" disabled
                   placeholder="请选择客户来源">
          </u-input>
          <u-icon slot="right" name="arrow-right"></u-icon>
          <u-picker :show="showC" :columns="customerSource" @confirm="confirmC" @cancel=" showC = false"/>
        </u-form-item>

        <u-form-item label="是否签约司机" borderBottom>
          <u-radio-group v-model="addbean.signedDriver" placement="row">
            <u-radio label="是" name="1"/>
            <u-radio label="否" name="0"/>
          </u-radio-group>
        </u-form-item>

        <u-form-item label="入职日期" borderBottom @click="handeClick('2')">
          <u-input v-model="addbean.joiningTime" inputAlign="right" disabled disabledColor="#ffffff"
                   border="none"
                   placeholder="请选择" type="select"></u-input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>

        <u-form-item label="开户行" borderBottom>
          <u-input v-model="addbean.openingBank" inputAlign="right" border="none" placeholder="请输入开户行">
          </u-input>
        </u-form-item>

        <u-form-item label="银行账号" borderBottom>
          <u-input v-model="addbean.bankAccount" inputAlign="right" border="none" placeholder="请输入银行账号">
          </u-input>
        </u-form-item>

        <u-form-item label="所属银行" borderBottom>
          <u-input v-model="addbean.affiliatedBank" inputAlign="right" border="none" placeholder="请输入所属银行">
          </u-input>
        </u-form-item>

        <u-form-item label="备注" borderBottom>
          <u-input v-model="addbean.note" inputAlign="right" border="none" placeholder="请输入备注">
          </u-input>
        </u-form-item>


        <!--        <u-form-item label="客户备注" borderBottom>-->
        <!--          <u-input v-model="addbean.note" inputAlign="right" border="none" placeholder="请输入客户备注">-->
        <!--          </u-input>-->
        <!--        </u-form-item>-->

        <view style="margin: 30rpx 0">
          <u-icon name="order" color="#1573FF" label="其他资料" label-color="#333333"></u-icon>
        </view>

        <u-form-item>
          <view class="car-photo" style="
              padding: 0 0 20rpx;
              display: block;
              font-size: 30rpx;
              color: #333;
            ">资料照片
          </view>
          <lr-upload tag="8" @on-change="uploadOnChange"></lr-upload>
        </u-form-item>
      </u-form>
    </view>

    <view style="height: 100rpx"></view>

    <u-datetime-picker :show="showDate" mode="date" @confirm="handleConfirm"
                       @cancel="showDate = false"/>

    <view class="button-container">
      <button class="btn-item" @click="bottomClick(1)">提交</button>
    </view>
  </view>
</template>

<script>
import lrUpload from "../../components/global/lr-upload.vue";
import gljyDataPicker from "@/components/gljy-data-picker/gljy-data-picker.vue";

export default {
  components: {
    lrUpload,
    gljyDataPicker,
  },

  computed: {
    handleLabel() {
      return function (val, list) {
        let obj = list[0].find(a => a.value === val)
        return obj?.text || ''
      }
    }
  },

  data() {
    return {
      selType: 0,
      addbean: {
        username: "",
        businessPersonId: "",
        customerName: "",
        address: "",
        idCardNo: "",
        driverValidity: "",
        driverNo: "",
        nowAddress: "",
        contactPerson: "",
        license: "",
        email: "",
        emergencyPerson: "",
        emergencyMobile: "",
        channelName: "",
        note: "",
        bankCardImg: "",
        driverImg: "",
        licenseImg: "",
        accessory: [],
        customerType: 2,
        idCardExpirydate: "",
        birthday: "",
        joiningTime: "",
        contactMobile: ""
      },
      requireStr: "",
      columnsSexList: [
        [
          {text: '男', value: '1'},
          {text: '女', value: '2'},
          {text: '未知', value: '3'}
        ]
        // ['男','女','未知']
      ],
      show: false,
      customerSource: [
        [
          {text: '长租', value: '1'},
          {text: '短租', value: '2'},
        ]
      ],
      showC: false,
      rules: {
        customerName: [
          {
            type: "string",
            required: true,
            message: "请输入企业名称",
            trigger: ["blur", "change"],
          },
        ],
        idCardNo: [
          {
            type: "string",
            required: true,
            message: "请输入身份证号",
            trigger: ["blur", "change"],
          },
        ],
        contactPerson: [
          {
            type: "string",
            required: true,
            message: "请输入联系人",
            trigger: ["blur", "change"],
          },
        ],
        contactMobile: [
          {
            required: true,
            message: "请输入联系电话",
            trigger: ['change', 'blur'],
          },
          {
            validator: (rule, value, callback) => {
              return   /^1[3-9]\d{9}$/.test(value);
            },
            message: '手机号码不正确',
            trigger: ['change', 'blur'],
          }
        ],
        emergencyPerson: [
          {
            type: "string",
            required: true,
            message: "请输入紧急联系人",
            trigger: ["blur", "change"],
          },
        ],
        emergencyMobile: [
          {
            type: "string",
            required: true,
            message: "请输入紧急联系电话",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              return   /^1[3-9]\d{9}$/.test(value);
            },
            message: '手机号码不正确',
            trigger: ['change', 'blur'],
          }
        ],
      },
      dateType: '',
      showDate: false
    };
  },

  onLoad() {
    this.addbean.username = this.$store.state.user.userInfo.username;
    this.addbean.businessPersonId = this.$store.state.user.userInfo.userId;

    uni.$on("getRes", (res) => {
      console.log("受到选择负责人了", res.username);
      this.addbean.username = res.username;
      this.addbean.businessPersonId = res.userId;
    });

    uni.$on("selChannel", (res) => {
      console.log("受到选择渠道商了", res.channelName);
      this.addbean.channelName = res.channelName;
      this.addbean.channelId = res.channelId;
    });
    this.getRequire();
  },

  methods: {
    handeClick(type) {
      this.dateType = type
      this.showDate = true
    },
    handleConfirm(e) {
      let time = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
      console.log()
      if (this.dateType === '1') {
        this.addbean.birthday = time
      }
      if (this.dateType === '2') {
        this.addbean.joiningTime = time
      }
      this.showDate = false
    },

    openShow(key) {
      this[key] = true
    },

    confirmSex(e) {
      this.addbean.sex = e.value[0].value
      this.show = false
    },

    confirmC(e) {
      this.addbean.customerSource = e.value[0].value
      this.showC = false
    },

    getRequire() {
      this.$u.api
          .sysConfigRequire("CUSTOMER_FORM_REQUIRED_FIELE")
          .then((res) => {
            this.requireStr = res?.paramValue ?? "";
            console.log("this.requireStr", this.requireStr);
          });
    },
    isRequire(field) {
      return this.requireStr.indexOf(field) >= 0;
    },

    //图片上传成功回调
    uploadOnChange(tag, resultList, resultObjList) {
      if (uni.$u.test.isEmpty(resultList)) {
        return;
      }

      resultList = resultList.map((item) => {
        // item = item.substring(this.baseImgUrl.length, item.length);
        return item;
      });

      this.handleOcr(tag, resultList, resultObjList)
      // switch (tag) {
      //   case "1": //驾驶证或营业执照
      //     if (0 == this.selType) {
      //       //驾驶证
      //       this.addbean.driverImg = resultList[0];
      //
      //       //调用自动识别接口
      //       this.getDriverCerInfo(resultList[0]);
      //     } else {
      //       //营业执照
      //       this.addbean.licenseImg = resultList[0];
      //     }
      //
      //     break;
      //
      //   case "2": //身份证
      //     this.addbean.idCardImg = resultList[0];
      //     this.getIdInfo(resultList[0]);
      //     break;
      //   case "3": //银行卡
      //     this.addbean.bankCardImg = resultList[0];
      //     break;
      //   case "8": //资料照片
      //     this.addbean.accessory = resultList;
      //     break;
      // }
    },

    //获取ocr
    handleOcr(tag, resultList, resultObjList) {
      switch (tag) {
        case '1': //身份证正面
          this.$set(this.addbean, 'idCardImg', resultList[0])
          this.getIdInfo(resultList[0], 'front');
          break;
        case '2': //身份证背面
          this.$set(this.addbean, 'idCardImgBack', resultList[0])
          this.getIdInfo(resultList[0], 'back');
          break;
        case '3': //行驶证正面
          this.$set(this.addbean, 'driverImg', resultList[0])
          this.getDriverCerInfo(resultList[0]);
          break;
        case '4': //行驶证背面
          this.$set(this.addbean, 'driverImgBack', resultList[0])
          break;
        case '5': //营业执照
          this.$set(this.addbean, 'licenseImg', resultList[0])
          break;
      }
    },


    //自动获取驾驶证信息
    getDriverCerInfo(imageUrl) {
      this.$u.api
          .getDrivingLicenceQueryNew({
            path: imageUrl,
          })
          .then((res) => {
            console.log("驾驶证识别信息", res);

            //将字符串转为date类型
            // let timeDate = new Date(res.licenseDate);
            //将date类型转为时间戳
            // let timestemp = timeDate.getTime();
            //将时间戳转为指定格式的字符串
            // let timeStr = this.$u.timeFormat(timestemp, 'yyyy-MM-dd');
            this.addbean.quasiDrivingType = res.carType;
            this.addbean.driverValidity = `${res.startTime}-${res.endTime}`;
            this.addbean.driverNo = res.driverNo;
          });
    },

    //自动获取身份证信息
    getIdInfo(imageUrl, type) {
      this.$u.api.getOcrIdCard({path: imageUrl, idCardSide: type}).then((res) => {
        if (type === 'front') { //正面
          this.addbean.customerName = res.name;
          this.addbean.idCardNo = res.idCard;
          this.addbean.address = res.address;
        }
        if (type === 'back') { //反面
          this.addbean.idCardExpirydate = res.endDate
        }
      });
    },

    //选择业务负责人
    selRes() {
      uni.navigateTo({
        url: "./buss_owner_list",
      });
    },

    //选择渠道商
    selchannel() {
      uni.navigateTo({
        url: "/pagesA/channel/sel-channel?type=2",
      });
    },

    //底部按钮的点击事件
    bottomClick(type) {
      let that = this;
      that.handleEffect()
          .then(() => {
            uni.showModal({
              title: "确定提交吗?",
              success(res) {
                if (res.confirm) {
                  that.$u.api.addCustomerInfor(that.addbean).then((res) => {
                    uni.$emit("addcustomer", true);
                    uni.showToast({
                      icon: "none",
                      title: "提交成功",
                    });

                    setTimeout(() => {
                      uni.navigateBack();
                    }, 1000);
                  });
                }
              },
            });
          })
          .catch(() => {
          });
      return;
      this.addbean.customerType = 0 == this.selType ? 2 : 1;

      if (this.$u.test.isEmpty(this.addbean.customerName)) {
        this.$u.toast("请输入客户名称");
        return;
      } else if (
          this.isRequire("idCardNo") &&
          this.$u.test.isEmpty(this.addbean.idCardNo)
      ) {
        this.$u.toast("请输入身份证号");
        return;
      } else if (this.$u.test.isEmpty(this.addbean.contactMobile)) {
        this.$u.toast("请输入联系电话");
        return;
      } else if (
          this.isRequire("emergencyPerson") &&
          this.$u.test.isEmpty(this.addbean.emergencyPerson)
      ) {
        this.$u.toast("请输入紧急联系人");
        return;
      } else if (
          this.isRequire("emergencyMobile") &&
          this.$u.test.isEmpty(this.addbean.emergencyMobile)
      ) {
        this.$u.toast("请输入紧急联系电话");
        return;
      } else {
        uni.showModal({
          title: "确定提交吗?",
          success(res) {
            if (res.confirm) {
              that.$u.api.addCustomerInfor(that.addbean).then((res) => {
                uni.$emit("addcustomer", true);
                uni.showToast({
                  icon: "none",
                  title: "提交成功",
                });

                setTimeout(() => {
                  uni.navigateBack();
                }, 1000);
              });
            }
          },
        });
      }
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.uForm
            .validate()
            .then((res) => {
              resolve();
            })
            .catch((errors) => {
              reject();
            });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .u-radio-group {
  display: flex;
  justify-content: flex-end;
}

.step-bg {
  width: 100%;
  height: 113rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: $xz-bgColor-write;

  text {
    width: 170rpx;
    text-align: center;
    line-height: 50rpx;
    border-radius: 8rpx;
    color: #333;
    font-size: 28rpx;
    border: #a7a7a7 1rpx solid;
  }
}

.uploadBg {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10rpx 150rpx;
}

.licesson-upload {
  display: flex;
  align-items: center;
}

.u-form {
  margin: 10px;
  padding: 22rpx;
  background-color: $xz-bgColor-write;
}

.u-input {
  font-size: 24rpx;
}

// .button-container {
// 	display: flex;
// 	position: fixed;
// 	width: 100%;
// 	height: 100rpx;
// 	bottom: 0;
// 	z-index: 999;
// 	background-color: white;
// 	display: flex;
// 	align-items: center;
// 	justify-content: space-around;
// }

.deptPicker {
  position: fixed;
  z-index: 9999;
}

// .button-container {
// 	display: flex;
// 	position: fixed;
// 	width: 100%;
// 	height: 100rpx;
// 	bottom: 0;
// 	z-index: 999;
// 	background-color: white;
// 	display: flex;
// 	align-items: center;
// 	justify-content: space-around;

// 	button {
// 		width: 90%;
// 		height: 80rpx;
// 		line-height: 80rpx;
// 		border-radius: 40rpx;
// 		color: $xz-bgColor-write;
// 		background-color: $xz-bgColor-blue;
// 	}

// }

.pic-content {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;

  .pic-item {
    // flex: 1;
    width: 300rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    // image {
    // 	height: 200rpx;
    // 	width: 100%;
    // }

    text {
      margin-top: 20rpx;
      color: #333;
      font-size: 24rpx;
    }
  }
}
</style>
